package com.fs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.entity.*;
import com.fs.mapper.*;
import com.fs.service.IAdministratorsService;
import com.fs.util.AdminContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.NumberFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-12
 */
@Service
public class  AdministratorsServiceImpl implements IAdministratorsService {
    @Autowired
    AdministratorsMapper administratorsMapper;
    @Autowired
    MaterialsMapper materialsMapper;
    @Autowired
    StudentsMapper studentsMapper;
    @Autowired
    ReviewersMapper reviewersMapper;
    @Autowired
    MaterialallocationMapper materialallocationMapper;
    @Autowired
    MaterialreviewMapper materialreviewMapper;
    @Override
    public ResponseData Login(String acount, String apassword) {
        QueryWrapper<Administrators> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("acount",acount);
        Administrators administrators=administratorsMapper.selectOne(queryWrapper);
        if (administrators==null){
            return ResponseData.error("用户不存在");
        }else if (administrators.getApassword().equals(apassword)){
            AdminContext.setAdmin(administrators);
            return ResponseData.ok(administrators);
        }
        return ResponseData.error("密码错误");
    }

    @Override
    public ResponseData Update(String newapassword, String newaphnumber, String newemail,int aid) {
        UpdateWrapper<Administrators> updateWrapper=new UpdateWrapper<>();
        Administrators administrators=AdminContext.getAdmin();
        if (administrators==null){
            return ResponseData.error("未登入");
        }
        updateWrapper.eq("aid",administrators.getAid());
        Administrators administratorForUpdate = new Administrators();
        administratorForUpdate.setApassword(newapassword); // 设置新密码
        administratorForUpdate.setAphnumber(newaphnumber); // 设置新电话号码
        administratorForUpdate.setEmail(newemail); // 设置新电子邮件
        int updateResult = administratorsMapper.update(administratorForUpdate,updateWrapper);
        if (updateResult>0){
            return ResponseData.ok(200,"修改成功");
        }
        return ResponseData.error("修改失败");
    }

    @Override
    public ResponseData Spotcheck() {
        QueryWrapper<Materials> queryWrapper=new QueryWrapper<>();
        queryWrapper.gt("state",2);
        List<Materials> list=materialsMapper.selectList(queryWrapper);
        int size =list.size();
        Random random=new Random();
        int number=random.nextInt(size);
        System.out.println(list.size());
        System.out.println(list.get(number));
        return ResponseData.ok(list.get(number));
    }

    @Override
    public ResponseData CheckIndepart(int ReqCredit) {
        QueryWrapper<Students> wrapper = new QueryWrapper<>();
        QueryWrapper<Students> swrapper=new QueryWrapper<>();
        // 使用select指定你想要查询的列，包括聚合函数和分组列
        wrapper.select("COUNT(*) as studentcount","departmentid");
        wrapper.groupBy("departmentid");
        swrapper.select("COUNT(*) as studentcount","departmentid");
        swrapper.ge("credit",ReqCredit);
        swrapper.groupBy("departmentid");
        List<Map<String, Object>> allList = studentsMapper.selectMaps(wrapper);
        List<Map<String, Object>> completelist=studentsMapper.selectMaps(swrapper);
        List<Map<String,Object>> resultList=new ArrayList<>();
        int count=allList.size();
        if (count==completelist.size()){
            for (int i=0;i<count;i++){
                long comple=(long)completelist.get(i).get("studentcount");
                long all=(long)allList.get(i).get("studentcount");
                int depart=(int)allList.get(i).get("departmentid");
                double percent=comple*1.00/all*100;
                Map<String, Object> entry = new HashMap<>();
                entry.put("departmentId", depart);
                entry.put("percentCompleted", percent);
                resultList.add(entry);
            }
        }else{

        }

        ResponseData responseData = new ResponseData();
        responseData.setData(resultList);
        return responseData;
    }

    @Override//查询班级完成情况
    public ResponseData CheckClass(int RequCredit) {
        QueryWrapper<Students> wrapper = new QueryWrapper<>();
        wrapper.select("COUNT(*) as studentcount","classname");
        wrapper.groupBy("classname");
        List<Map<String, Object>> allList = studentsMapper.selectMaps(wrapper);
        List<Map<String, Object>> completelist=administratorsMapper.selectThanInClass(RequCredit);
        for (Map<String, Object> map : completelist) {
            if (!map.containsKey("studentcount") || map.get("studentcount") == null) {
                int i=0;
                map.put("studentcount", 0);
                map.put("classname",completelist.get(i).get("classname"));
                        i++;
            }
        }
        List<Map<String,Object>> resultList=new ArrayList<>();
        int count=allList.size();

        for (int i=0;i<count;i++){
            int classes=(int)allList.get(i).get("classname");
            for (int j=0;j<count;j++){
                if (classes==(int)completelist.get(j).get("classname")){
                    long comple=(long)completelist.get(j).get("studentcount");
                    long all=(long)allList.get(i).get("studentcount");
                    double percent=comple*1.0/all*1.0;
                    String percentS;
                    NumberFormat numberFormat  = NumberFormat.getPercentInstance();
                    numberFormat.setMinimumFractionDigits(2);
                    percentS=numberFormat.format(percent);
                    Map<String, Object> entry = new HashMap<>();
                    entry.put("className", classes);
                    entry.put("percentCompleted", percentS);
                    resultList.add(entry);
                }
            }
        }
        ResponseData responseData = new ResponseData();
        responseData.setData(resultList);
        return responseData;
    }

    @Override//预警查询到了学分小于credit值的学生
    public ResponseData Warm(int credit) {
        QueryWrapper<Students> wrapper=new QueryWrapper<>();
        wrapper.lt("credit",credit);
        List<Students> list=studentsMapper.selectList(wrapper);
        System.out.println(list);
        return ResponseData.ok(list);
    }

    @Override//改
    public ResponseData CheckallmaterialsInclass(int classname) {
       List<Materials> materials=new ArrayList<>();
       materials=administratorsMapper.CheckClassNameMaterials(classname);
        return ResponseData.ok(materials);
    }

    @Override//审核人员以及工作进度
    public ResponseData ShowReviewers() {
      List<CheckReviewers> checkReviewersList=reviewersMapper.CheckR();
      List<ReviewersShow> reviewersShowList=new ArrayList<>();
      for (int i=0;i<checkReviewersList.size();i++){
          ReviewersShow reviewersShow=new ReviewersShow();
          CheckReviewers checkReviewers=checkReviewersList.get(i);
          reviewersShow.setRid(checkReviewers.getRid());
          reviewersShow.setRname(checkReviewers.getRname());
          reviewersShow.setRemail(checkReviewers.getRemail());
          reviewersShow.setAll(checkReviewers.getAudited()+checkReviewers.getUnaudited());
          reviewersShow.setComplete(checkReviewers.getAudited());
          reviewersShow.setRphnumber(checkReviewers.getRphnumber());
          NumberFormat numberFormat  = NumberFormat.getPercentInstance();
          numberFormat.setMinimumFractionDigits(2);
          if (reviewersShow.getAll()==0){
              reviewersShow.setCompleteprogress(0.0);
              reviewersShow.setPercent("没有分配材料");
          }else{
              reviewersShow.setCompleteprogress(reviewersShow.getComplete()*1.0/reviewersShow.getAll()*1.0);
              reviewersShow.setPercent(numberFormat.format(reviewersShow.getCompleteprogress()));
          }
          reviewersShowList.add(reviewersShow);
      }
      if (reviewersShowList!=null){
          return ResponseData.ok(reviewersShowList);
      }else
          return ResponseData.error("查询失败");
    }

    @Override//催促
    public ResponseData urge(int rid[]) {
        QueryWrapper<Reviewers>wrapper=new QueryWrapper<>();
        List<Reviewers> resultlist=new ArrayList<>();
        for (int i=0;i<rid.length;i++){
            wrapper.clear();
           wrapper.eq("rid",rid[i]);
            Reviewers reviewer=reviewersMapper.selectOne(wrapper);
            resultlist.add(reviewer);
        }
        return ResponseData.ok(resultlist);
    }

    @Override//对于审核人员动态查询
    public Page<ReviewersShow> SelectReviwersBynameAndid(ReviewersCondition condition) {
        Page<Reviewers> page=Page.of(1,3);
        if (condition.getCurrentpage()!=null){
            page.setCurrent(condition.getCurrentpage());
        }
        Page<Reviewers> ReviewersPage= reviewersMapper.SelectReviewrsByPage(page,condition);
        int size=ReviewersPage.getRecords().size();
        List<ReviewersShow> reviewersShowList=new ArrayList<>();
        List<CheckReviewers> checkReviewersList=reviewersMapper.CheckR();
        for (int i=0;i<size;i++){
            Reviewers reviewers=ReviewersPage.getRecords().get(i);
            for (int j=0;j<checkReviewersList.size();j++){
                CheckReviewers checkReviewers= checkReviewersList.get(j);
                if (reviewers.getRid()==checkReviewers.getRid()){
                    ReviewersShow reviewersShow=new ReviewersShow();
                    reviewersShow.setRid(checkReviewers.getRid());
                    reviewersShow.setRname(checkReviewers.getRname());
                    reviewersShow.setRemail(checkReviewers.getRemail());
                    reviewersShow.setAll(checkReviewers.getAudited()+checkReviewers.getUnaudited());
                    reviewersShow.setComplete(checkReviewers.getAudited());
                    reviewersShow.setRphnumber(checkReviewers.getRphnumber());
                    NumberFormat numberFormat  = NumberFormat.getPercentInstance();
                    numberFormat.setMinimumFractionDigits(2);
                    if (reviewersShow.getAll()==0){
                        reviewersShow.setCompleteprogress(0.0);
                        reviewersShow.setPercent("没有分配材料");
                    }else{
                        reviewersShow.setCompleteprogress(reviewersShow.getComplete()*1.0/reviewersShow.getAll()*1.0);
                        reviewersShow.setPercent(numberFormat.format(reviewersShow.getCompleteprogress()));
                    }
                    reviewersShowList.add(reviewersShow);
                }
            }
        }
        Page<ReviewersShow>pageS=new Page<>();
        pageS.setSize(2);pageS.setRecords(reviewersShowList);pageS.setCurrent(1);pageS.setTotal(reviewersShowList.size());
        return pageS;
    }
}
